package com.online.fund.spider;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import com.online.fund.spider.dao.FundDao;
import com.online.fund.spider.entity.IndustryPlate;
import com.online.fund.util.DateUtils;
import com.online.fund.util.HttpClientUtil;

import jdk.nashorn.api.scripting.ScriptObjectMirror;

/**
 * 获取行业板块数据
 * 
 * @author galen.zhang
 *
 */
@Component
@SuppressWarnings("restriction")
public class IndustryPlateProcesser {

	private final static Logger logger = LoggerFactory.getLogger(IndustryPlateProcesser.class);

	@Resource
	private FundDao fundDao;

	private final static String INDUSTRY_PLATE_PAGE_URL = "http://nufm.dfcfw.com/EM_Finance2014NumericApplication/JS.aspx?type=CT&cmd=C._BKHY&sty=FPGBKI&sortType=(ChangePercent)&sortRule=-1&page=1&pageSize=100&js=var%20nsSjabFw%3d%7brank:[(x)],pages:(pc),total:(tot)%7d&token=7bc05d0d4c3c22ef9fca8c2a912d779c&jsName=quote_123&_g=0.628606915911589&_=1518188023666";

	public void parsePage() {
		parsePage(true);
	}

	public void parsePage(boolean saveFlag) {
		try {
			String crawlDate = DateUtils.getCurrentDate();
			String resultStr = HttpClientUtil.httpGetRequest(INDUSTRY_PLATE_PAGE_URL);
//			System.out.println(resultStr);

			ScriptEngineManager scriptEngineManager = new ScriptEngineManager();
			ScriptEngine nashorn = scriptEngineManager.getEngineByName("nashorn");

			nashorn.eval(resultStr);
			ScriptObjectMirror db = (ScriptObjectMirror) nashorn.get("nsSjabFw");
			ScriptObjectMirror datas = (ScriptObjectMirror) db.get("rank");
			if (datas.isArray()) {

				List<IndustryPlate> industryPlateList = new ArrayList<IndustryPlate>();

				// 删除数据
				if (saveFlag) {
					fundDao.deleteIndustryPlate(crawlDate);
				}
				
				for (int i = 0; i < datas.size(); i++) {
					String data = (String) datas.get("" + i);
//					System.out.println(data);
					String[] dataArr = data.split(",");
					
					IndustryPlate industryPlate = new IndustryPlate();
					industryPlate.setCrawlDate(crawlDate);
					industryPlate.setIndustryPlateCode(dataArr[1]);
					industryPlate.setIndustryPlateName(dataArr[2]);
					
					// 最新价、涨跌额、涨跌幅、市值、换手率
					industryPlate.setLatestPrice(Double.parseDouble(dataArr[18]));
					industryPlate.setChangeAmount(Double.parseDouble(dataArr[19]));
					industryPlate.setRiseFallRate(Double.parseDouble(dataArr[3]));
					industryPlate.setMarketValue(new BigDecimal(dataArr[4]));
					industryPlate.setTurnoverRate(Double.parseDouble(dataArr[5]));
					
					// 上涨家数
					String[] increaseNumberArr = dataArr[6].split("\\|");
					industryPlate.setIncreaseNumber(Integer.parseInt(increaseNumberArr[0]));
					industryPlate.setDownNumber(Integer.parseInt(increaseNumberArr[2]));
					
					// 领涨股票名称、领涨股票类型，1:上证、2:深证、领涨股票最新价、领涨股票涨跌幅
					industryPlate.setLeadSharesCode(dataArr[7]);
					industryPlate.setLeadSharesName(dataArr[9]);
					industryPlate.setLeadSharesType(Integer.parseInt(dataArr[8]));
					industryPlate.setLeadSharesLatestPrice(Double.parseDouble(dataArr[10]));
					industryPlate.setLeadSharesRiseFallRate(Double.parseDouble(dataArr[11]));
					
					// 领跌股票名称、领跌股票类型，1:上证、2:深证、领跌股票最新价、领跌股票涨跌幅
					industryPlate.setLedDownSharesCode(dataArr[12]);
					industryPlate.setLedDownSharesName(dataArr[14]);
					industryPlate.setLedDownSharesType(Integer.parseInt(dataArr[13]));
					industryPlate.setLedDownSharesLatestPrice(Double.parseDouble(dataArr[15]));
					industryPlate.setLedDownSharesRiseFallRate(Double.parseDouble(dataArr[16]));
					
					industryPlateList.add(industryPlate);
				}
				
				if (saveFlag) {
					fundDao.batchAddIndustryPlate(industryPlateList);
				} else {
					System.out.println(industryPlateList.get(0));
				}
				
			}

		} catch (Exception e) {
			logger.error("获取行业板块数据错误", e);
		} finally {
			HttpClientUtil.closeConnectionPool();
		}

	}

	public static void main(String[] args) throws Exception {
		IndustryPlateProcesser processer = new IndustryPlateProcesser();
		processer.parsePage(false);
		
	}
}
